package han.chensing.latos.maker.latos.file.transform;

import han.chensing.latos.maker.latos.file.transform.impl.melody.MelodyTransformer;
import han.chensing.latos.common.level.LatosProject;
import han.chensing.latos.common.level.util.StreamUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

public class ProjectTransformerManager {

    private static ProjectTransformerManager manager;

    public static ProjectTransformerManager getInstance() {
        if (manager==null)manager=new ProjectTransformerManager();
        return manager;
    }

    private final List<Class<? extends ProjectTransformer>> projectTransformers;

    public ProjectTransformerManager(){
        this.projectTransformers=new ArrayList<>();
        init();
    }

    private void init(){
        register(MelodyTransformer.class);
    }

    private void register(Class<? extends ProjectTransformer> projectTransformerClass){
        projectTransformers.add(projectTransformerClass);
    }

    public LatosProject genProject(File file){
        try {
            String name = file.getName();
            String suffix = StreamUtil.getSuffix(name);
            if (suffix==null)return null;
            suffix=suffix.toLowerCase(Locale.ROOT);
            for (Class<? extends ProjectTransformer> projectTransformerClass : projectTransformers) {
                SupportSuffix annotation = projectTransformerClass.getAnnotation(SupportSuffix.class);
                if (annotation==null)continue;
                String[] value = annotation.value();
                if (contains(value,suffix)){
                    ProjectTransformer projectTransformer = (ProjectTransformer) projectTransformerClass.getConstructors()[0].newInstance();
                    return projectTransformer.genLatosProject(file);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    private boolean contains(String[] value,String suffix){
        for (String s : value)
            if (s.equalsIgnoreCase(suffix))return true;
        return false;
    }

}
